package com.bionic.banking.commands;

import com.bionic.banking.auth.manager.Config;
import com.bionic.banking.auth.manager.Message;
import com.bionic.banking.dao.connection.LoggerLoader;
import com.bionic.banking.logic.controller.UserController;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CommandLogin implements ICommand {

    private static final String LOGIN = "login";
    private static final String PASSWORD = "password";
    private static final org.apache.log4j.Logger logger = LoggerLoader.getLogger(CommandLogin.class);

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException {

        String page = null;
        String login = request.getParameter(LOGIN);
        String password = request.getParameter(PASSWORD);
           
        //Check if session active
        HttpSession session = request.getSession(false);
        String session_user = session != null 
                            ? (String) session.getAttribute(Config.USER_SESSION_KEY)
                            : null;       

        UserController bean;
        try {
            bean = new UserController();
            try {
                //Save user to session instead of request.setAttribute("user", login)
                if (bean.verify(login, password)) 
                {
                    session = request.getSession(true);
                    session.setAttribute(Config.USER_SESSION_KEY, login);
                    page = Config.getInstance().getProperty(Config.MAIN);
                } else {
                    request.setAttribute("error",
                            Message.getInstance().getProperty(Message.LOGIN_ERROR));
                    page = Config.getInstance().getProperty(Config.ERROR);
                }
            } catch (SQLException ex) {
                logger.error(ex);
                request.setAttribute("error", ex.getMessage());
                page = Config.getInstance().getProperty(Config.ERROR);
            }
        } catch (InstantiationException | IllegalAccessException ex) {
            logger.error(ex);
            request.setAttribute("error", ex.getMessage());
            page = Config.getInstance().getProperty(Config.ERROR);
        }

        return page;
    }
}
